<template>
    <el-main >
        <!-- 搜索栏 -->
         <el-form :model="searchParm"  :inline="true" size="default" >
            <el-form-item  >
                <el-input placeholder="请输入姓名" v-model="searchParm.nickName"></el-input>
            </el-form-item>
            <el-form-item >
                <el-input placeholder="请输入电话" v-model="searchParm.phone"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button icon="Search" @click="searchBtn">搜索</el-button>
                <el-button icon="Close" @click="resetBtn">重置</el-button>
                <el-button v-permission="['sys:user:add']" icon="Plus" type="primary" @click="addBtn">新增</el-button>
            </el-form-item>
         </el-form>
         <!-- 表格 -->
          <el-table :height="tableHeight" :data="tableList" border stripe>
            <el-table-column align="center" prop="image" label="头像">
                <template #default = "scope">
                     <el-image v-if="scope.row.image"
                     style="width: 80px; height: 80px; border-radius: 50%;" 
                     :src="imgbase+scope.row.image.split(',')[0]"/>             
                </template>
            </el-table-column>
          
            <el-table-column prop="nickName" label="姓名"></el-table-column>
            <el-table-column prop="deptName" label="科室"></el-table-column>
            <el-table-column prop="sex" label="性别">
                <template #default="scope">
                    <el-tag v-if="scope.row.sex == '0'" type="primary" size="default"  effect="dark" closable>男</el-tag>
                    <el-tag v-if="scope.row.sex == '1'" type="danger" size="default"  effect="dark" closable>女</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="username" label="账户"></el-table-column>
            <el-table-column prop="phone" label="电话"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="visitAddress" label="出诊地址"></el-table-column>
            <el-table-column prop="toHome" label="推荐首页">
                <template #default="scope">
                    <el-tag v-if="scope.row.toHome == '0'" type="danger" size="default"  effect="dark" closable>未推荐</el-tag>
                    <el-tag v-if="scope.row.toHome == '1'" type="primary" size="default"  effect="dark" closable>推荐</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="enabled" label="启用状态">
                <template #default="scope">
                    <el-switch 
                    v-model="scope.row.enabled" 
                    :active-value="true" 
                    :inactive-value="false" 
                    :before-change="beforeStatus.bind(global,scope.row)"
                    @change="changeStatus(scope.row.userId)"
                    style="
                    --el-switch-on-color:#13ce66;
                    --el-switch-off-color:#ff7670;
                    ">
                    </el-switch>   
                </template>
            </el-table-column>
            <el-table-column  label="操作" align="center" width="320px">
                <template #default="scope" >
                    <el-button v-permission="['sys:user:edit']" type="primary" icon="Edit" size="default" @click="editBtn(scope.row)">编辑</el-button>
                    <el-button v-permission="['sys:user:reset']" type="warning" icon="Setting" size="default" @click="resetPasswordBtn(scope.row.userId)">重置密码</el-button>
                    <el-button v-permission="['sys:user:delete']" type="danger" icon="Delete" size="default" @click="deleteBtn(scope.row.userId)">删除</el-button>
                </template> 
            </el-table-column>
          </el-table>
          <!-- 分页 -->
       <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page.sync="searchParm.currentPage"
        :page-sizes="[10 ,20, 40, 80, 100]"
        :page-size="searchParm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchParm.total" background>
        
       </el-pagination>
         <!-- 新增编辑 -->
          <SysDialog
          :title="dialog.title"
          :width="dialog.width"
          :height="dialog.height"
          :visible="dialog.visible"
          @on-close="onClose"
          @on-confirm="commit"
          >
            <template v-slot:content>
                <el-form 
                :model="addModel" 
                ref="addForm" 
                :rules="rules"
                label-width="85px"  
                :inline="false" 
                size="default">
                    <el-row >
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="nickName" label="姓名：" >
                                <el-input v-model="addModel.nickName" ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="sex" label="性别：" >
                               <el-radio-group v-model="addModel.sex" >
                                <el-radio :label="'0'" >男</el-radio>
                                <el-radio :label="'1'" >女</el-radio>
                               </el-radio-group> 
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row >
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="education" label="学历：" >
                                <el-input v-model="addModel.education" ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="jobTitle" label="职称：" >
                                <el-input v-model="addModel.jobTitle" ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <el-row >
                    <el-col :span="12" :offset="0">
                            <el-form-item prop="phone" label="电话：" >
                                <el-input v-model="addModel.phone" ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="email" label="邮箱：" >
                                <el-input v-model="addModel.email" ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row >
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="roleId" label="角色：" >
                                <SelectChecked
                                ref="selectRef" 
                                :options="options"
                                :bindValue="bindValue"
                                @selected="selected">
                            </SelectChecked>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="depyId" label="科室：" >
                                
                                  <el-select 
                                  v-model="addModel.deptId" 
                                  clearable
                                  style="width: 100%;"
                                  aria-placeholder="请选择科室">
                                    <el-option
                                      v-for="item in deptOptions"
                                      :key="item['value']"
                                      :label="item['label']"
                                      :value="item['value']">
                                    </el-option>
                                  </el-select>
                                
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                    <el-col :span="12" :offset="0">
                            <el-form-item prop="username" label="账户：" >
                                <el-input v-model="addModel.username" ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="password" label="密码：" >
                                <el-input v-model="addModel.password" ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row >
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="price" label="挂号费：" >
                                <el-input type="number" v-model="addModel.price" ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" :offset="0">
                            <el-form-item prop="toHome" label="推荐首页：" >
                                <el-radio-group v-model="addModel.toHome">
                                    <el-radio  :label="'0'" >否</el-radio>
                                    <el-radio  :label="'1'" >是</el-radio>
                                </el-radio-group>
                               
                            </el-form-item>
                        </el-col>
                    </el-row>
                            <el-form-item prop="introduction" label="简介：" >
                                <el-input :row="3" type="textarea" 
                                v-model="addModel.introduction" ></el-input>
                            </el-form-item> 
                            <el-form-item prop="goodAt" label="擅长：" >
                                <el-input :row="3" type="textarea" 
                                v-model="addModel.goodAt" ></el-input>
                            </el-form-item> 
                            <el-form-item prop="visitAddress" label="出诊地址：" >
                                <el-input :row="3" type="textarea" 
                                v-model="addModel.visitAddress" ></el-input>
                            </el-form-item> 
                            <el-form-item prop="image"  label="头像" >
                                <UploadImage
                                ref="upImgRef"
                                @getImg="getImg"
                                :oldUrl="oldUrl"
                                :fileList="fileList">
                                </UploadImage>
                            </el-form-item>
                </el-form>
            </template>
          </SysDialog>
         
    </el-main>
    
</template>

<script setup lang="ts">
import { reactive,ref } from 'vue';
import SysDialog from '../../../components/SysDialog.vue';
import useDialog from '../../../hooks/useDialog';
import UploadImage from '../../../components/UploadImage.vue';
import { type NewType } from '../../../type/BaseType';
import { getSelectDeptApi } from '../../../api/department';
import { ElMessage, type FormInstance,type UploadUserFile } from 'element-plus';
import SelectChecked from '../../../components/SelectChecked.vue';
import { getSelectApi} from '../../../api/role/index'
import { onMounted } from 'vue';
import { addApi, getListApi,getRoleListApi,deleteApi, editApi,resetPasswordApi, enabledApi } from '../../../api/user';
import { nextTick } from 'vue';
import type {User} from '../../../api/user/UserModel';
import useInstance from '../../../hooks/useInstance';
import { computed } from 'vue';
const imgbase = computed(()=>{
   return 'http://localhost:8089'
})
//获取全局的global
const {global} = useInstance()

//表格高度
const tableHeight = ref(0)
const selectRef = ref()
//弹框属性
const {dialog,onClose,onShow} =useDialog();
//搜索栏绑定对象
const searchParm = reactive({
    phone:'',
    nickName:'',
    currentPage:1,
    pageSize:10,
    total:0,
});
const deptOptions = ref([])
//查询科室下拉数据
const getSelectDept = async()=>{
    let res =await getSelectDeptApi();
    if(res && res.code == 200){
        deptOptions.value = res.data;
    }
}
//表单对象
const addModel = reactive({
    userId:'',
    username:'',
    password:'',
    phone:'',
    email:'',
    sex:'',
    nickName:'',
    roleId:'',
    deptId:'',
    deptName:'',
    education:'',
    jobTitle:'',
    image:'',
    introduction:'',
    visitAddress:'',
    toHome:'',
    goodAt:'',
    price:''
})
//表单ref属性
const addForm = ref<FormInstance>()
//表单规则
const rules =reactive({
    nickName:[
        {
            required:true,
            message:"请输入角色名称",
            trigger:"change",
        }],
        sex:[
        {
            required:true,
            message:"请选择性别",
            trigger:"change",
        }],
        education:[
        {
            required:true,
            message:"请输入学历",
            trigger:"change",
        }],
        jobTitle:[
        {
            required:true,
            message:"请输入职称",
            trigger:"change",
        }],
    phone:[
        {
            required:true,
            message:"请填写电话",
            trigger:"change",
        }],
        price:[
        {
            required:true,
            message:"请填写挂号费",
            trigger:"change",
        }],
    email:[
        {
            required:true,
            message:"请填写邮箱",
            trigger:"change",
        }],
     roleId:[{
             required:true,
            message:"请选择角色",
             trigger:"change",
     }],
    username:[
        {
            required:true,
            message:"请填写账号",
            trigger:"change",
        }],
    password:[
        {
            required:true,
            message:"请填写密码",
            trigger:"change",
        }],
        deptId:[{
             required:true,
            message:"请选择科室",
             trigger:"change",
     }],
     image:[
        {
            required:true,
            message:"请上传图片",
            trigger:"change",
        }],
        introduction:[
        {
            required:true,
            message:"请填写简介",
            trigger:"change",
        }],
        visitAddress:[
        {
            required:true,
            message:"请填写出诊地址",
            trigger:"change",
        }],
        goodAt:[
        {
            required:true,
            message:"请填写医生擅长病症",
            trigger:"change",
        }],
})
const upImgRef = ref();
const fileList = ref<Array<UploadUserFile>>([])
const oldUrl = ref<Array<{url:string}>>([])
const imgUrl = ref<Array<{url:string}>>([])
const getImg = (img:NewType) =>{
    console.log(img)
    imgUrl.value = oldUrl.value.concat(img.newImgUrl)
    if(img.deleteUrl.length >0){
        let newArr = imgUrl.value.filter(
            (x)=>!img.deleteUrl.some((item)=>x.url === item.url)
        )
        imgUrl.value = newArr;
    }
    let url = '';
    for(let k=0;k< imgUrl.value.length;k++){
        
        url = url + imgUrl.value[k].url +',';
    }
    addModel.image = url.substring(0,url.lastIndexOf(','))
}
//下拉表单数据定义
let options =ref([]) 
//表单勾选的值
const selected = (value:Array<string | number>) =>{
    console.log(value.join(','))
    addModel.roleId = value.join(',')
}
//查询角色下拉数据
const getSelect =async()=>{
    let res = await getSelectApi()
    if(res && res.code == 200){
        options.value = []
        options.value = res.data;
    }

}
const tableList = ref([])
//列表
const getList = async()=>{
    let res = await getListApi(searchParm)
    if(res && res.code == 200){
        tableList.value = res.data.records;
        searchParm.total = res.data.total;
    }
}
const searchBtn = () =>{
    getList()
}
const resetBtn = () =>{
    searchParm.nickName = ''
    searchParm.currentPage = 1
    getList()
}
//页数改变时
const sizeChange = (size:number)=>{
    searchParm.pageSize = size;
    getList()
}
//页数改变时触发
const currentChange =(page:number)=>{
    searchParm.currentPage = page;
    getList()

}
//用户拥有的角色id
const bindValue = ref([])
const roleIds = ref('')
//根据用户id查询角色
const getRoleList = async(userId:string)=>{
   let res = await getRoleListApi(userId)
   if(res && res.code == 200){
    bindValue.value = res.data;
    roleIds.value = res.data.join(',')
        
    }
}
const tags = ref('')
//新增按钮
const addBtn = async() =>{
    //清空图片
    fileList.value=[]
    oldUrl.value = []
    tags.value = '0'
    dialog.title = '新增';
    dialog.height = 400;
    dialog.width = 900;
    await getSelectDept()
    onShow();
    //清空下拉数据
    options.value = []
    bindValue.value = []
    //获取下拉数据
    await getSelect() 
 
 nextTick(()=>{
    //清空下拉数据
    selectRef.value.clear()
 })
 //清空表单
 addForm.value?.resetFields()
 
}
//编辑
const editBtn = async(row:User) =>{
    //清空图片
    fileList.value=[]
    oldUrl.value = []
    tags.value = '1'
    //清空下拉数据
    options.value = []
    bindValue.value = []
    //获取下拉数据
    await getSelect()
    dialog.height = 400;
    dialog.width = 900;
    await getSelectDept()
    //查询角色id
    await getRoleList(row.userId)
    dialog.title = '编辑';
 onShow();
 nextTick(()=>{
    //数据回显
    Object.assign(addModel,row)
    addModel.roleId = roleIds.value
    
    //图片回显
    if(addModel.image){
        let imgs = addModel.image.split(',')
        for(let i = 0;i<imgs.length;i++){
            let img ={name:"",url:""};
            img.name = imgs[i];
            img.url = "http://localhost:8089"+imgs[i];
            fileList.value.push(img);
            oldUrl.value.push({url:imgs[i]})
        }
    }

 })
 
 //清空表单
 addForm.value?.resetFields()
}
const resetPasswordBtn = async(userId:string)=>{
    console.log(userId)
  console.log(global)
  const confirm = await global.$myconfirm('确定重置密码为【123456】吗?')
  console.log(confirm)
  if(confirm){
    let res = await resetPasswordApi({userId:userId})
    if(res && res.code == 200){
        ElMessage.success(res.msg)
        //刷新列表
        getList()
    }
    
  }
}
//删除
const deleteBtn=async(userId:string)=>{
  console.log(userId)
  console.log(global)
  const confirm = await global.$myconfirm('是否要删除该角色')
  console.log(confirm)
  if(confirm){
    let res = await deleteApi(userId)
    if(res && res.code == 200){
        ElMessage.success(res.msg)
        //刷新列表
        getList()
    }
    
  }
}
//提交表单
const commit = () => {
  //验证表单
  addForm.value?.validate(async(valid)=>{
    if(valid){
        console.log('验证通过')
        let res = null
        if(tags.value == '0'){
            res = await addApi(addModel)
        }else{
            res = await editApi(addModel)
        }

        if(res && res.code == 200){
            ElMessage.success(res.msg)
            onClose()
        }
        getList()
    }
  })
}
const switchTags = ref('')
const switchParm = reactive({
    userId:'',
    enabled:false
})
const beforeStatus = async(row:any)=>{
    const confirm = await global.$confirm(
        row.enabled?'确定停用该用户吗':'确定启用该用户吗'
    )
    return new Promise((resolve,reject)=>{
        if(confirm){
            switchTags.value = "confirm"
            switchParm.userId = row.userId;
            switchParm.enabled = !row.enabled;
            return resolve(confirm)
        }else{
            return reject(confirm)
        }
    })
}
const changeStatus = async(userId:string)=>{
    console.log("进入了")
    if(switchTags.value == 'confirm'){
        console.log(userId)
        try{
            let res =await enabledApi(switchParm)
            if(res && res.code == 200){
                getList()
                ElMessage.success(res.msg)
            }
        }catch{
            getList()
        }
    }
}

onMounted(()=>{
//
getList();
nextTick(()=>{
tableHeight.value = window.innerHeight - 230
});
}
)
</script>

<style lang="scss" scoped>

</style>